import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Test extends HttpServlet {
	private Configuration cfg;

	/**
	 * Constructor of the object.
	 */
	public Test() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * d The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String qword;
		String currentPageNo = "1";

		if (request.getParameter("qword") == null) {
			qword = "";
		}else{
			qword = request.getParameter("qword");
//			qword = new String(request.getParameter("qword").getBytes("ISO-8859-1"), "UTF-8");
		}
		if (request.getParameter("page") != null) {
			if (!"".equals(request.getParameter("page"))) {
				currentPageNo = request.getParameter("page");
			}
		}
		try {
			Result rs = new Result();
			Map root = new HashMap();
			if(!"".equals(qword)){
				String xml = this.invokeApi(qword, currentPageNo);
				
				XStream xstream = new XStream(new StaxDriver());
				xstream.alias("result", Result.class);
				xstream.alias("song", Song.class);
				xstream.aliasAttribute(Result.class, "time", "time");
				xstream.aliasAttribute(Result.class, "length", "length");
	
				if (!"".equals(xml)) {
					rs = (Result) xstream.fromXML(xml);
				}
				
				root.put("qword", qword);
				root.put("pagelink",
						this.creatPagelink(Integer.parseInt(currentPageNo), Integer.parseInt(rs.getLength()) / 20, qword));
			}
		
			root.put("rs", rs);
			root.put("hosturl", request.getHeader("HOST"));
			root.put("pageno", currentPageNo);
			
			Template template = cfg.getTemplate("SearchDemo.html");
			response.setContentType("text/html;charset=UTF-8");// 设定字符集，否则有汉字乱码
			Writer out = response.getWriter();

			// 1.用Enviroment
			Environment env = template.createProcessingEnvironment(root, out);
			env.setClassicCompatible(true);
			env.process();
			// 2.template.process(root, out);//两种方法都可以

			// out.flush();//清除缓冲区
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// request.getParameter(arg0)

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		super.init();
		cfg = new Configuration();

		cfg.setServletContextForTemplateLoading(getServletContext(), "");
	}

	public String creatPagelink(int currentPageNo, int maxPageNo, String qword) {
		try {
			qword = URLEncoder.encode(qword, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
		currentPageNo = currentPageNo > maxPageNo ? maxPageNo : currentPageNo;
		int begainNo = currentPageNo - 5 > 0 ? currentPageNo - 5 : 1;
		int endNo = begainNo + 9 > maxPageNo ? maxPageNo : begainNo + 9;
		StringBuffer bf = new StringBuffer();
		if (maxPageNo > 1) {
			bf.append(begainNo > 1 ? ("<a href = \"./test?qword=" + qword + "&page="
					+ (currentPageNo - 1 > 1 ? currentPageNo - 1 : 1) + "\" class=\"next-button\">上一页</a>&nbsp") : "");
			for (int i = begainNo; i <= endNo; i++) {
				
				if(i==currentPageNo){
					
					bf.append("<a href = \"./test?qword=" + qword + "&page=" + i + "\" class=\"pressed-button\">" + i
							+ "</a>&nbsp");
				}else
				bf.append("<a href = \"./test?qword=" + qword + "&page=" + i + "\" class=\"page-button\">" + i
						+ "</a>&nbsp");
			}
			bf.append(endNo < maxPageNo ? ("<a href = \"./test?qword=" + qword + "&page="
					+ (currentPageNo + 1 > maxPageNo ? maxPageNo : currentPageNo + 1) + "\" class=\"next-button\">下一页</a>") : "");
			return bf.toString();
		}
		return "";

	}
	
	public String invokeApi(String qword, String currentPageNo){
		StringBuffer xml = new StringBuffer("");
		try {
			String urlencoded_qword = URLEncoder.encode(qword, "UTF-8");
			URL url = new URL(
					"http://218.200.230.77/searchinterface/search?searcher=musiclabel&num=20&sorter=1&keyword="
							+ urlencoded_qword + "&page=" + currentPageNo);
			
			
//			URL url = new URL(
//			"http://localhost/searchinterface/search?searcher=musiclabel&num=20&sorter=1&keyword="
//					+ urlencoded_qword + "&page=" + currentPageNo);
	
			
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
			String s;
			while ((s = in.readLine()) != null) {
				xml.append(s);
			}
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml.toString();
	}

	public static void main(String[] args) {

		Test t = new Test();
		System.out.println(t.creatPagelink(91, 100, "搜索"));
	}

}
